import { defineConfig, loadEnv, PluginOption } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
import tsconfigPaths from 'vite-tsconfig-paths';
import { viteMockServe } from 'vite-plugin-mock';

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
    const env = loadEnv(mode, process.cwd(), 'VITE_APP');
    const envWithProcessPrefix = Object.entries(env).reduce((prev, [key, val]) => {
        return {
            ...prev,
            ['process.env.' + key]: `"${val}"`
        };
    }, {});

    // Inject NODE_ENV and make sure envWithProcessPrefix is not empty
    envWithProcessPrefix['process.env.NODE_ENV'] = `'${mode}'`;

    const devPlugins: PluginOption[] = [];

    if ('development,test'.split(',').indexOf(mode) != -1) {
        console.info('mock start');
        devPlugins.push(
            viteMockServe({
                supportTs: true
            })
        );
    }

    return {
        plugins: [...devPlugins, reactRefresh(), tsconfigPaths()],
        define: envWithProcessPrefix,
        server: {
            port: 3000,
            proxy: {
                '/api': {
                    target: 'http://localhost:3000',
                    changeOrigin: true,
                    rewrite: (path: string) => path.replace(/^\/api/, '')
                }
            }
        }
    };
});
